package com.mytools.test;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import org.apache.poi.ss.usermodel.*;
import org.jsoup.internal.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class Pinterest {
    public static void main(String[] args) {
//        String proxyHost = "127.0.0.1";
        String proxyHost = "192.168.68.78";
        String proxyPort = "2013";
//        System.setProperty("socks.proxyHost", proxyHost);
//        System.setProperty("socks.proxyPort", proxyPort);
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", proxyPort);
        List<List<?>> rows =new ArrayList<>();
        List<String> headRow = CollUtil.newArrayList("id", "url", "image", "grid_title", "link", "display_description");
        rows.add(headRow);
        String book="";
        for(int i=0;i<10;i++){
            try {

                book=req(rows,book);
                if(book==null || "".equals(book)){
                    break;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        WriteCsvFile("D:\\File\\", rows);
        System.out.println("ok");
    }

    public static String req(List<List<?>> rows,String book){
        String data="{\"options\":{\"article\":null,\"appliedProductFilters\":\"---\",\"auto_correction_disabled\":false,\"corpus\":null,\"customized_rerank_type\":null,\"filters\":null,\"query\":\"fabric sofa\",\"query_pin_sigs\":null,\"redux_normalize_feed\":true,\"rs\":\"ac\",\"scope\":\"pins\",\"source_id\":null,\"no_fetch_context_on_resource\":false},\"context\":{}}";
        if(!StringUtil.isBlank(book)){
            data="{\"options\":{\"article\":null,"+"\"bookmarks\":[\""+book+"\"],"+"\"appliedProductFilters\":\"---\",\"auto_correction_disabled\":false,\"corpus\":null,\"customized_rerank_type\":null,\"filters\":null,\"query\":\"fabric sofa\",\"query_pin_sigs\":null,\"redux_normalize_feed\":true,\"rs\":\"ac\",\"scope\":\"pins\",\"source_id\":null,\"no_fetch_context_on_resource\":false},\"context\":{}}";
        }
        HttpRequest req= HttpUtil.createPost("https://www.pinterest.com/resource/BaseSearchResource/get");
        req.header("cookie","csrftoken=1eb42b6bce7cde00dcdb113549aa5b18; _routing_id=\"3d019577-00dd-47b5-beb3-998a6a591ea8\"; g_state={\"i_l\":0}; _auth=1; _pinterest_sess=TWc9PSZMcUNiai9aQmgvenEyaG9VclZXZXhEUEdwQjExdDgwa0Q5L2h5YmFzQXlWUFQ0Z3RLbDJPVGtPWmdsaEdpKzZyMzhiQjNFYTNwN21vc3Q1Yjhkc3hjS0IxWVNYRUoyMnFuNGx1SUtGMDUrSkpTTmc1Q08xT051U2p6QXlPd3ZudW43UEhTVWVKaFBjM29Vc0JBTjNGSGVsUWx1MG4xZkxZT3JEVzNhbE5kWHJmS3djdVV2Q3RDKzh0dkVUNDJuM0pvS0oyY1Bob2JZU1ZtVWtrUmRHNUMvYkt5bEdvckd1U2V0UnFxZHB6ZmRpMloreDZHL2pRQ0p0eXFwbGpkNGR3NWpUSjNNNWhNNmdZTk5SN2VNVWFQQjhXQm5nN1JPVC94SkMxNTl2ODVJakFod2lEYXJoK3Rzdk1ZQ25sNXVNa1l2SlVERjlpYk9zdkFsVEhDNnNTQXE3OG1ucURURUI5eW90Q2RSVHB3aVV3S1lHc0pHdVFYMWJ1WStwa0V6YjF0VDZNUmhybER5bVdEODFwZ3dmTVhwa0gwY3hvb2pQUHJYckEwSi9xM2hpUEdqdTVMSkFYYlhyWGNqU0VlRExtbGcvYXQ2emNyK21WTmh6S1NZMTh4VkJialB2czNnK0tnbEQ1bHF6T3Z1cjB6QjRFa0p1WHlJYXNiTmRBZXpUS0JJZnZRVlZjd05CejA0S0dqbGNzelAwam5Hb3RmYzh5UFloVWhmK2VWZFRPeFdyQTRlMGl3VU1FbWx0emRCRUd2dktrbXRUSkNBakJad2kwQTRFT1lyYXJjMjQyVWpSajhTOUlud1lzc0xydjVQNk1hTm1pWTk4M0UxZGtCWTdaa01NZ2taZXhBWlV1Q0cxd2dNa0xaR2pxS3ZOSjhjQlNjSzAyaTZKQmhOR2hheFZXU3ZzZlo0Q3JCMkI1Ymc2QmNrL2xnY2Nac0YzSGtSbEIvaWNEOVR3VjYydzRCb2EwdE05Z0VHVzIrYmxCM0RyeTZ2YVZjSjdmZ0lZQVFGN2JCU1V2eE1JWjV4Sm9GMmtpeGlpTTJnPT0mUWxMYWtTa0xMR2g3YTZrUmFJdHZJdG5raUI0PQ==; _b=\"AWQZlSNwKjxGH7qSWGByUP+Bo6YFfKLPbczT+e+APukmhgMbSVYfZfwzG6jZ0wyhh1s=\"; cm_sub=none");

        req.header("x-csrftoken","1eb42b6bce7cde00dcdb113549aa5b18");
//        req.header("ContentType","application/json");

        req.form("source_url","/search/pins/?rs=ac&len=2&q=fabric%20sofa&eq=fabric%20sofa&etslf=2106&term_meta[]=fabric%7Cautocomplete%7C0&term_meta[]=sofa%7Cautocomplete%7C0");
        req.form("data",data);

        String s=req.execute().body();
        if(JSONUtil.isTypeJSONObject(s)){
            JSONObject obj=JSONUtil.parseObj(s);
            Object s1= obj.getByPath("resource_response.data.results");
            if(s1==null){
                return null;
            }
            List<JSONObject> beans=(List)s1;
            for(JSONObject bean:beans){
                if(!"pin".equals(bean.get("type"))){
                    continue;
                }

                List<?> row = CollUtil.newArrayList(bean.get("id"), "https://www.pinterest.com/pin/"+bean.get("id")+"/",
                        bean.getByPath("images.orig.url"), bean.get("grid_title"),
                        bean.getByPath("link"), bean.getByPath("rich_summary.display_description"));
                rows.add(row);
            }
            return obj.getByPath("resource_response.bookmark")+"";
        }
        return null;
    }

    public static void WriteCsvFile(String path, List<List<?>> rows) {
        try {
//            File fout = new File(path + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".xlsx");
//            if (!fout.getParentFile().exists()&&!fout.isDirectory()){
//                fout.getParentFile().mkdirs();
//            }
//            FileOutputStream fos = new FileOutputStream(fout);
//            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
//            bw.write(sb.toString());
//            bw.newLine();
//            bw.flush();
//            bw.close();

            String fileName =path + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".xlsx";
            BigExcelWriter writer = ExcelUtil.getBigWriter(fileName);

            //设置内容字体
            Font font = writer.createFont();
//            font.setBold(true);
            font.setColor(Font.COLOR_NORMAL);
//            font.setItalic(true);

            //默认单元格样式
            CellStyle defauleStyle = writer.getCellStyle();
            defauleStyle.setFont(font);
//            defauleStyle.set

//            //头部样式
//            CellStyle headStyle = writer.getHeadCellStyle();
//            StyleUtil.setColor(headStyle, IndexedColors.BLUE, FillPatternType.SOLID_FOREGROUND);
//
//            //数字样式
            CellStyle numberStyle = writer.getStyleSet().getCellStyle();
//            StyleUtil.setColor(numberStyle, IndexedColors.BLACK, FillPatternType.SOLID_FOREGROUND);
            StyleUtil.setAlign(numberStyle, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
//
//            //日期样式
//            CellStyle dateStyle = writer.getStyleSet().getCellStyleForDate();
//            StyleUtil.setColor(dateStyle, IndexedColors.DARK_YELLOW, FillPatternType.SOLID_FOREGROUND);

            //写入表头
//            writer.writeHeadRow(headRow);

            // 一次性写出内容，使用默认样式
            rows.forEach(k -> {
                writer.writeRow(k);
            });
            // 关闭writer，释放内存
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
